<template>
    <el-dialog @close="onClose" :model-value="dialogVisible" title="分配角色" width="30%" draggable>
        <el-select v-model="value" multiple placeholder="Select" style="width: 240px">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onCancel">取消</el-button>
                <el-button type="primary" @click="onConfirm">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import * as http from "@/request/http"
import { ElMessage } from 'element-plus';
import { ref, watch } from 'vue'

const value = ref<number[]>([])
const options = ref<roleList[]>([])
const props = withDefaults(defineProps<{
    dialogVisible: boolean
    id: number
}>(), {
    dialogVisible: false,
    id: 0
})

http.role.roleListAll().then(res => {
    options.value = res.data
})

watch(
    () => props.id,
    () => {
        if (props.id != 0) {
            http.admin.getAdminRole(props.id).then(res => {
                value.value = res.data.map(item => item.id)
            })
        }
    }
)

const emits = defineEmits<{
    (e: "cancel"): void
    (e: "confirm"): void
}>()

const onConfirm = () => {
    if (props.id != 0) {
        http.admin.adminRoleUpdate({
            roleIds: value.value,
            adminId: props.id
        }).then(() => {
            emits("confirm")
            ElMessage.success("提交成功")
        })
    }
}

const onClose = () => {
    emits("cancel")
}

const onCancel = () => {
    emits("cancel")
}
</script>

<style scoped></style>